import axios from 'axios'
import { Message, Loading } from 'element-ui'

// const url = '/' //线上
const url = 'http://172.16.68.113:8080/swagger-ui.html' //倪有才
// 创建axios实例
const service = axios.create({
  baseURL: url, // 线上环境
  timeout: 30000, // 请求超时时间
  withCredentials: true
})
// request拦截器
service.interceptors.request.use(
  config => {
    config.headers = {
      "Content-Type": "application/json",
      "X-Requested-With": "XMLHttpRequest",
      "UCATEGORY_CODE": (config.data && config.data.UCATEGORY_CODE) || (config.params && config.params.UCATEGORY_CODE) || sessionStorage.getItem('UCATEGORY_CODE')
    }
    if (config.data && config.data.UCATEGORY_CODE) delete config.data.UCATEGORY_CODE;
    if (config.params && config.params.UCATEGORY_CODE) delete config.params.UCATEGORY_CODE;
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data;
    if (res.code !== 200 && res.code !== 0) {
      Message({ showClose: true, duration: 2000, type: 'error', message: res.message || res.msg });
      return Promise.reject(new Error(res.message || res.msg || 'Error'))
    } else if (res.code == 5) {
      return Promise.reject(new Error(res.message || res.msg || 'Error'))
    } else {
      return res;
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({ message: error.message, type: 'error', duration: 3 * 1000 })
    return Promise.reject(error)
  }
)

export default (options, { loading = false, message = '加载中' } = {}) => {
  let loadingInstance
  if (loading) {
    loadingInstance = Loading.service({ text: message })
  }
  return new Promise((resolve, reject) => {
    service(options).then(resolve).catch(reject).finally(() => {
      if (loading) {
        loadingInstance.close()
      }
    })
  })
}
